<?php
/*
    nspire-gamekit - a simple homebrew game framework
    Copyright (C) 2011  Daniel Tang

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    NIMG Specifications:
    4 bytes: magic string
    2 bytes: little endian number
    4 bytes: uint32 width
    4 bytes: uint32 height
    
*/

if ($argc != 3) {
    printf(
    "Script to convert images to NIMG\n".
    "Usage: php %s input output \n",
    $argv[0]);
    die();
}


function rgb2gray($r, $g, $b, $alpha, $bits) {
    $lume = ((0.2989 * $r) + (0.5870 * $g) + (0.1140 * $b))/255;
    return ($lume*(pow(2,$bits)-1)) | (($alpha*(pow(2,$bits)-1))<<4); 
}
$ifilename=$argv[1];
$ofilename=$argv[2];

if (!file_exists($ifilename)) {
    die("Filename does not exist\n");
}

$img = new Imagick($ifilename);
$header = pack("a*vVV","NIMG",0x00FF,$img->getImageWidth(),$img->getImageHeight());
$imgdata = "";

$iterator = $img->getPixelIterator();

$array = $iterator->getCurrentIteratorRow();
while ($array != NULL) {
    foreach($array as $pixel) {
        $color = $pixel->getColor();
        $imgdata .= pack("C",rgb2gray(
            $color['r'],
            $color['g'],
            $color['b'],
            $color['a'],4));
    }
    try {
        $array = $iterator->getNextIteratorRow();
    } catch (ImagickPixelIteratorException $exp) {
    } 
}

file_put_contents($ofilename.".tns", $header.$imgdata);
die("File saved to ".$ofilename.".tns\n");

?>
